package com.jsgt.greekfire.ui.pool

import android.graphics.drawable.BitmapDrawable
import android.os.Handler
import android.os.Message
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher

import android.widget.EditText
import android.widget.PopupWindow
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.RecyclerView
import com.fhx.core.base.BaseFragment
import com.fhx.core.goToActivity
import com.fhx.core.utils.PriceFormatUtil
import com.fhx.core.utils.ScreenUtil
import com.fhx.core.utils.ToastUtils
import com.jsgt.greekfire.*
import com.jsgt.greekfire.bean.MinerBean
import com.jsgt.greekfire.event.PoolEvent
import com.jsgt.greekfire.factory.UserViewModelFactory
import com.jsgt.greekfire.ui.home.entrance.EntranceActivity
import com.jsgt.greekfire.ui.pool.adapter.MinerAdapter
import com.jsgt.greekfire.ui.pool.incomerecord.IncomeRecordListActivity
import com.jsgt.greekfire.ui.pool.transfercoin.TransferCoinActivity1
import com.jsgt.greekfire.viewmodel.UserViewModel

import kotlinx.android.synthetic.main.fragment_pool.*
import kotlinx.android.synthetic.main.fragment_pool.pool_header_view
import kotlinx.android.synthetic.main.view_pool_header1.*

import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 矿池
 */
class PoolFragment : BaseFragment() {
    private val userViewModel: UserViewModel by lazy {
        ViewModelProvider(
            this,
            UserViewModelFactory()
        ).get(UserViewModel::class.java)
    }
    private val searchMinerAdapter by lazy { MinerAdapter() }
    private val minerAdapter by lazy { MinerAdapter() }
    private var popupWindow: PopupWindow? = null
    private var searchEdit: EditText? = null
    private var minerList: List<MinerBean>? = null
    private var minerBean: MinerBean? = null
    private var currentPage = 0
    private var isRefresh = true
    private  var isPoolActive=false
    val handler: Handler by lazy {
        object : Handler() {
            override fun handleMessage(msg: Message) {
                if (msg.what == 1) {
                    val str = searchEdit?.text.toString().trim()
                    if (LOGIN_STATUS && !TextUtils.isEmpty(str)) {
                        userViewModel.searchMinerList(
                            str,
                            PAGE_START,
                            PAGE_SIZE * 5//此处不分页
                        )
                    }
                }
            }
        }
    }

    override fun getLayoutId(): Int = R.layout.fragment_pool
    override fun onResume() {
        super.onResume()
        initData()
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            initData()
        }
    }

    private fun initData() {
        if (LOGIN_STATUS) {
            userViewModel.totalCoinNumber()
            userViewModel.poolData()
            userViewModel.myCoinNumber()
            userViewModel.coinPoolList(PAGE_START, PAGE_SIZE)

        }
        userViewModel.poolActIsStart()
    }

    fun resetData() {
        person_income_tv.text = "0"
        team_income_tv.text = "0"

        person_income_tv2.text = "0"
        person_income_tv3.text = "0"
        person_income_tv4.text = "0"
        person_income_tv5.text = "0"
//
//        coin_num_tv.text = getString(R.string.currency_held) + "：0.0"
//        person_calcu_tv.text = getString(R.string.holding_power) + "：0"
//        team_coin_tv.text = getString(R.string.currency_held) + "：0.0"
//        team_calcu_tv.text = getString(R.string.computing_power) + "：0"
//
//        activation_num_tv.text = getString(R.string.Miner_address) + " 0"
//        team_device_num_tv.text = getString(R.string.Name_equipment) + " 0"
//        dir_num_tv.text = getString(R.string.Direct_miner) + " 0"
//        today_all_tv.text = "0"
//        all_calcu_tv.text = "0"
//        promotion_calcu_tv.text = "0"
        total_pool_tv.text = "0"
//
        minerAdapter.clearData()
    }

    override fun main() {
      setTopPadding(pool_header_view)



        pool_rv.adapter = minerAdapter

        refresh_layout.setOnRefreshListener {
            isRefresh = true
            initData()
            userViewModel.coinPoolList(currentPage + 1, PAGE_SIZE)
        }

        roll_in_or_out_tv.setOnClickListener {

//            ToastUtils.show(context!!, "活动未开始")
            if (LOGIN_STATUS) {
                if (IS_ACTIVATION == 1) {
                    ToastUtils.show(context!!, getString(R.string.account_no_activation))
                } else {
                    if (minerBean != null) {
                        if(isPoolActive){
                            goToActivity<TransferCoinActivity1>()
                        }else{
                            ToastUtils.show(context!!, "活动未开始")
                        }

                    } else {
                        ToastUtils.show(context!!, "数据异常，请稍微重试")
                    }
                }
            } else {
                EntranceActivity.start(context!!)
            }
        }


//        search_tv.setOnClickListener {
//            if (LOGIN_STATUS) {
//                popupWindow?.showAtLocation(search_tv, Gravity.NO_GRAVITY, 0, 0)
//                searchEdit?.requestFocus()
//                search_tv.postDelayed({
//                    val inputManager =
//                        context!!.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
//                    inputManager.showSoftInput(searchEdit, 0)
//                }, 500)
//            } else {
//                EntranceActivity.start(context!!)
//            }
//
//        }
        userViewModel.searchMinerListLiveData.observe(this, Observer {
            searchMinerAdapter.refreshData(it)
            refresh_layout.isRefreshing = false

        })

        userViewModel.poolActBoolean.observe(this, Observer {
            refresh_layout.isRefreshing=false;
            if(it==null){

            }
            else{
                if(it==0){
                   isPoolActive=false
                }
                else if(it ==1) {
                    isPoolActive=true
                }
            }
        });
        userViewModel.coinPoolListLiveData.observe(this, Observer {
            refresh_layout.isRefreshing = false
            minerList = it
            if (it == null) {

            } else {
                if (isRefresh) {
                    if (it.isNotEmpty()) {
                        currentPage = 1
                    }
                    minerAdapter.refreshData(it)
                } else {
                    if (it.isNotEmpty()) {
                        currentPage++
                    }

                    minerAdapter.addData(it)
                }
                //这里不隐藏，否则不能触发上下滑动
                if (minerAdapter.dataList().size > 0) {

                }
            }
        })
        userViewModel.totalCoinNumberLiveData.observe(this, Observer {
            refresh_layout.isRefreshing = false

            total_pool_tv.text = PriceFormatUtil.format(it.toDouble(), 4)
        })
        userViewModel.myCoinNumberLiveData.observe(this, Observer {
            refresh_layout.isRefreshing = false
            minerBean = it
            person_income_tv.text ="+"+ PriceFormatUtil.format(it.income!!, 4)
            person_income_tv2.text =  it.warehouse?.toDouble()?.toInt().toString()
            person_income_tv3.text = PriceFormatUtil.format(it.calculating!!, 4)
            team_income_tv.text = "+"+PriceFormatUtil.format(it.teamIncome!!, 4)

            person_income_tv4.text = it.teamWarehouse?.toDouble()?.toInt().toString()
            person_income_tv5.text = PriceFormatUtil.format(it.teamCalculating!!, 4)
        })
        userViewModel.minerTotalLiveData.observe(this, Observer {
            refresh_layout.isRefreshing = false
            if (it == 0) {
                minerAdapter.clearData()
            }
//            activation_num_tv.text = getString(R.string.Miner_address) + it
        })
        userViewModel.teamDeviceNumLiveData.observe(this, Observer {
            refresh_layout.isRefreshing = false
//            team_device_num_tv.text = getString(R.string.Name_equipment) + it
        })
        userViewModel.directPushNumLiveData.observe(this, Observer {
            refresh_layout.isRefreshing = false
//            dir_num_tv.text = getString(R.string.Direct_miner) + it
        })
        userViewModel.poolDataLiveData.observe(this, Observer {
            refresh_layout.isRefreshing = false
            today_all_tv.text = PriceFormatUtil.format(it.chanchu!!, 4)
            all_calcu_tv.text = PriceFormatUtil.format(it.single!!, 4)
            promotion_calcu_tv.text = PriceFormatUtil.format(it.team!!, 4)
        })
        userViewModel.errorLiveData.observe(this, Observer {
            refresh_layout.isRefreshing = false
        })
        initSearchWindow()

        income_record_tv.setOnClickListener {
            if (LOGIN_STATUS) {
                if (IS_ACTIVATION == 1) {
                    ToastUtils.show(context!!, getString(R.string.account_no_activation))
                } else {
                    goToActivity<IncomeRecordListActivity>()
                }
            } else {
                EntranceActivity.start(context!!)
            }
        }

    }

    private fun initSearchWindow() {
        val contentView = layoutInflater.inflate(R.layout.view_search_miner, null, false)
        contentView.findViewById<TextView>(R.id.cancel).setOnClickListener {
            dismissWindow()
        }
        searchEdit = contentView.findViewById(R.id.search_edit)
        searchEdit?.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                handler.removeMessages(1)
                handler.sendEmptyMessageDelayed(1, 500)
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}

        })
        val minerRv = contentView.findViewById<RecyclerView>(R.id.miner_rv)
        minerRv.adapter = searchMinerAdapter
        popupWindow = PopupWindow(
            contentView,
            ScreenUtil.getScreenWidth(context!!),
            ScreenUtil.getScreenHeight(context!!)
        )
        popupWindow?.isFocusable = true
        popupWindow?.setBackgroundDrawable(BitmapDrawable())//这行代码是必须的,否则按系统返回键无法dismiss
        popupWindow?.setOnDismissListener {
            searchEdit?.setText("")
            searchMinerAdapter?.clearData()
        }


    }


    private fun dismissWindow() {
        popupWindow?.dismiss()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onPoolEvent(e: PoolEvent) {
        if (LOGIN_STATUS) {
            userViewModel.totalCoinNumber()
            userViewModel.myCoinNumber()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        popupWindow = null
    }
}